
// 接收两个参数，一个是接口url,一个是需要传给后端的数据
let $ajax = {
  "get": function(url, params) {
    //console.log(params)
    return this.methods(url, params, "GET", 'application/json')
  },
  "post": function(url, params) {
    //console.log(params)
    return this.methods(url, params, "POST", "application/x-www-form-urlencoded")
  },
  methods: function(url, params, method, headerMessage) {
    return new Promise(function(resolve, reject) {
      wx.request({
        url: url,
        method: method,
        header: {
          "Content-Type": headerMessage
        },
        data: params,
        success(res) {
          resolve(res)
        },
        fail(res) {
          reject(res)
        }
      })
    })
  }
}
// 删除指定id
Array.prototype.del = function (filter) {
  var index = filter;
  if (typeof filter == 'function') {
    for (var i = 0; i < this.length; i++) {
      if (filter(this[i], i)) index = i;
    }
  }
  this.splice(index, 1)
};

// 返回图片本地路径
function File(src, id = '') {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url: src,
      success(res) {
        resolve({
          id: id,
          src: res.tempFilePath
        })
      },
      fail(res) {
        reject(res)
      }
    })
  })
}
// 中心弹框
function CenterWindow(title, content) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title,
      content: content,
      showCancel: true,
      success(res) {
        if (res.confirm) {
          resolve(res)
        } else if (res.cancel) {
          reject(res)
        }
      }
    })
  });
}

// 消息弹框
function Popup(title, icon = 'success', image = '', duration = 100000) {
  return new Promise((resolve, reject) => {
    wx.showToast({
      title: title,
      icon: icon,
      image: image,
      duration: duration,
      mask: true,
      success(res) {
        resolve(res)
      }
    })
  })
}

function throttle(fn, gapTime = 1500, token) {
  let _lastTime = null
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  // var key = wx.getStorageSync('key')
  // console.log(key)
  // if (key == '' || key == undefined) {
  //   wx.redirectTo({
  //     url: '../pages/Super/Super',
  //   })
  // }
  // 返回新的函数
  return function() {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments, token) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
// 是否播放音乐, Type为1 是按键音，2是背景音乐
class musicKey {
  // 安全模式检测
  constructor(Source, Type) {
    if (this instanceof musicKey) {
      this.muisc_switch = wx.getStorageSync('music');
      this.Source = Source;
      this.Type = Type;
      this.innerAudioContext = wx.createInnerAudioContext();
    } else {
      return new musicKey(muisc_switch, Source, Type, innerAudioContext)
    }

  }
  // 传入一个值，判断是否暂停或者播放 isPlaying ==1 为播放，2 为暂停
  startMusic(isPlaying) {
    console.log('进入音乐播放')
    if (this.Type == 1 && this.muisc_switch) {
      // 按键声
      console.log('按键声音')
      this.innerAudioContext.src = this.Source;
      this.innerAudioContext.autoplay = true;
      this.innerAudioContext.volume = 1
    } else if (this.Type == 2 && this.muisc_switch) {
      console.log(this.innerAudioContext)
      this.innerAudioContext.src = this.Source;
      this.innerAudioContext.autoplay = true;
      this.innerAudioContext.loop = true
      this.innerAudioContext.volume = 0.3
    }
    // 背景音循环

  }
  // 停止音乐
  StopMusic() {
    console.log(this.innerAudioContext)
    this.innerAudioContext.stop();
  }
}
// 倒计时
class Timer {
  // 结束时间，更新时间，回调函数
  constructor(end, update, handle) {
    const now = new Date().getTime();
    const self = this;
    if (now - end) {
      handle.call(this);
    } else {
      let last_time = end - now;
      const px_d = 1000 * 60 * 60 * 24;
      const px_h = 100 * 60 * 60;
      const px_m = 1000 * 60;
      const px_s = 1000;
      let d = Math.floor(last_time / px_d);
      let h = Math.floor((last_time - d * px_d) / px_h);
      let m = Math.floor((last_time - d * px_d - h * px_h) / px_m)
      let s = Math.floor((last_time - d * px_d - h * px_h - m * px_m) / px_s);
      let r = [];
      if (d > 0) {
        r.push(`<em>${d}</em>天`)
      }
      if (r.length || h > 0) {
        r.push(`<em>${h}</em>`)
      }
      if (r.length || m > 0) {
        r.push(`<em>${m}</em>`)
      }
      if (r.length || s > 0) {
        r.push(`<em>${s}</em>`)
      }
      self.last_time = r.join('');
      update.call(self, r.join(''));
      setTimeout(function() {
        self.countdown(end, update, handle)
      }, 1000)
    }
  }
}

// post


// 支付接口
function Pay(url, Object) {
  return new Promise((resolve, reject) => {
    this.post(url, data).then((res) => {
      wx.requestPayment({
        timeStamp: res.data.data.timeStamp,
        nonceStr: res.data.data.nonceStr,
        package: 'prepay_id=' + res.data.data.prepayId,
        signType: 'MD5',
        paySign: res.data.data.sign,
        fail: function(aaa) {
          wx.showToast({
            title: '支付失败:' + aaa
          })
        },
        success: function() {
          wx.showToast({
            title: '支付成功'
          })
          wx.reLaunch({
            url: redirectUrl
          });
        }
      })
    })
  })


}
export {
  CenterWindow,
  Popup,
  throttle,
  File,
  musicKey,
  $ajax
}